package com.eques.util

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.text.TextUtils
import android.util.Log
import androidx.core.app.ActivityCompat

object NetConnctioUtils {
    /**
     * 判断wifi开关是否开启
     *
     * @param mWifiManager
     * @return
     */
    fun isWifiOpened(mWifiManager: WifiManager): Boolean {
        return mWifiManager.isWifiEnabled
    }

    /**
     * 打开或关闭wifi开关
     *
     * @param mWifiManager
     * @param enabled
     */
    fun openWiFiSw(mWifiManager: WifiManager, enabled: Boolean) {
        mWifiManager.setWifiEnabled(enabled)
    }

    /**
     * 判断WIFI网络是否可用
     *
     * @param context
     * @return
     */
    fun isWifiConnected(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        val state = wifiNetworkInfo!!.state
        return NetworkInfo.State.CONNECTED == state
    }

    /**
     * 判断MOBILE网络是否可用
     *
     * @param context
     * @return
     */
    fun isMobileConnected(context: Context?): Boolean {
        var bo = false
        if (context != null) {
            val connectMgr =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            if (networkInfo != null) {
                val state = networkInfo.state
                if (NetworkInfo.State.CONNECTED == state) {
                    bo = true
                }
            }
        }
        return bo
    }

    /**
     * 获取当前网络连接的类型信息
     *
     * @param context
     * @return
     */
    fun getConnectedType(context: Context?): Int {
        if (context != null) {
            val mConnectivityManager = context
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mNetworkInfo = mConnectivityManager.activeNetworkInfo
            if (mNetworkInfo != null && mNetworkInfo.isAvailable) {
                return mNetworkInfo.type
            }
        }
        return -1
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    @JvmStatic
    fun isNetworkConnected(context: Context): Boolean {
        val connectivity = context
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (connectivity == null) {
        } else {
            val info = connectivity.allNetworkInfo
            if (info != null) {
                for (i in info.indices) {
                    if (info[i].state == NetworkInfo.State.CONNECTED) {
                        Log.d("network", "ok")
                        return true
                    }
                }
            }
        }
        Log.d("network", "error")
        return false
    }

    //权限请求码
    const val PERMISSION_REQUEST_CODE = 0

    //两个危险权限需要动态申请（wifi、定位）
    val NEEDED_PERMISSIONS = arrayOf(
        Manifest.permission.ACCESS_COARSE_LOCATION
    )

    /**
     * 检查是否已经授予权限
     *
     * @return
     */
    fun checkPermission(activity: Activity?): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //如果 API level 是大于等于 23(Android 6.0) 时
            for (permission in NEEDED_PERMISSIONS) {
                if (ActivityCompat.checkSelfPermission(activity!!, permission)
                    != PackageManager.PERMISSION_GRANTED
                ) {
                    requestPermission(activity)
                    return false
                }
            }
        }
        return true
    }

    /**
     * 申请权限
     */
    fun requestPermission(activity: Activity?) {
        ActivityCompat.requestPermissions(
            activity!!,
            NEEDED_PERMISSIONS, PERMISSION_REQUEST_CODE
        )
    }


    /**
     * 获取当前连接WIFI的SSID
     *
     * @param mWifiManager
     * @return
     */
    fun getCurrentWifiSSID(mWifiManager: WifiManager?): String {
        if (mWifiManager != null) {
            val winfo = mWifiManager.connectionInfo
            if (winfo != null) {
                val s = winfo.ssid
                if (s.length > 2 && s[0] == '"' && s[s.length - 1] == '"') {
                    return s.substring(1, s.length - 1)
                }
            }
        }
        return ""
    }

    fun getCurrentWifiRssi(mWifiManager: WifiManager?): Int {
        if (mWifiManager != null) {
            val winfo = mWifiManager.connectionInfo
            if (winfo != null) {
                return winfo.rssi
            }
        }
        return -50
    }

    /**
     * 获取当前连接WIFI的BSSID
     * @param mWifiManager
     * @return
     */
    fun getCurrentWifiBSSID(mWifiManager: WifiManager?): String {
        if (mWifiManager != null) {
            val winfo = mWifiManager.connectionInfo
            if (winfo != null) {
                val s = winfo.bssid
                /*if (s.length() > 2 && s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
                    return s.substring(1, s.length() - 1);
                }*/if (!TextUtils.isEmpty(s)) {
                    return s
                }
            }
        }
        return ""
    }

    /**
     * 获取当前网络的ip地址
     *
     * @param mWifiManager
     * @return
     */
    fun getCurrentWifiIpAdress(mWifiManager: WifiManager?): String {
        if (mWifiManager != null) {
            val winfo = mWifiManager.connectionInfo
            if (winfo != null) {
                val ipAddress = winfo.ipAddress
                return formatIpAddress(ipAddress)
            }
        }
        return ""
    }

    private fun formatIpAddress(ipAdress: Int): String {
        return (ipAdress and 0xFF).toString() + "." +
                (ipAdress shr 8 and 0xFF) + "." +
                (ipAdress shr 16 and 0xFF) + "." +
                (ipAdress shr 24 and 0xFF)
    }

    /**
     * 判断wifi是否连接5G频段网络
     *
     * @param mWifiManager
     * @return
     */
    fun isCon5GHz(mWifiManager: WifiManager, wifiAccount: String): Boolean {
        @SuppressLint("MissingPermission") val scanResults = mWifiManager.scanResults
        try {
            if (!scanResults.isEmpty()) {
                for (scanResult in scanResults) {
                    val ssid = scanResult.SSID
                    if (ssid!="" && wifiAccount!="" && wifiAccount == ssid) {
                        val frequency = scanResult.frequency
                        return frequency > 4900 && frequency < 5900
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 获取当前连接的wifi名称
     *
     * @param context
     * @return
     */
    fun getWiFiSSID(context: Context): String {
        val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (wm != null) {
            val info = wm.connectionInfo
            if (info != null) {
                val s = info.ssid
                if (s.length > 2 && s[0] == '"' && s[s.length - 1] == '"') {
                    return s.substring(1, s.length - 1)
                }
            }
        }
        return ""
    }
    /**
     * 获取当前连接的wifi名称
     *
     * @param context
     * @return
     */
    /**
     * 判断当前选择的wifi是否是隐藏网络
     *
     * @param context
     * @param currentFillContent // 当前填写的WiFi名称
     * @return
     */
    fun isHiddenNet(context: Context, currentFillContent: String): Boolean {
        val wm = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (wm != null) {
            val info = wm.connectionInfo
            if (info != null) {
                val bssid = info.bssid
                return if (currentFillContent!="" && bssid!=""
                ) {
                    if (currentFillContent == bssid) {
                        info.hiddenSSID
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
        }
        return false
    }

    /**
     * 判断定位服务是否开启
     *
     * @param
     * @return true 表示开启
     */
    fun isLocationEnabled(context: Context): Boolean {
        var locationMode = 0
        val locationProviders: String
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            locationMode = try {
                Settings.Secure.getInt(context.contentResolver, Settings.Secure.LOCATION_MODE)
            } catch (e: SettingNotFoundException) {
                e.printStackTrace()
                return false
            }
            locationMode != Settings.Secure.LOCATION_MODE_OFF
        } else {
            locationProviders = Settings.Secure.getString(
                context.contentResolver,
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED
            )
            !TextUtils.isEmpty(locationProviders)
        }
    }

    @SuppressLint("MissingPermission")
    fun getCurrentWifiConfiguration(wifiManager: WifiManager): WifiConfiguration? {
        var currentSSID = wifiManager.connectionInfo.ssid
        if (currentSSID != null) {
            currentSSID = currentSSID.replace("\"", "")
            for (config in wifiManager.configuredNetworks) {
                if (config.SSID != null && config.SSID == "\"" + currentSSID + "\"") {
                    return config
                }
            }
        }
        return null
    }
}
